

class HuginNetStructureWriter:

    def __init__(self):
        self.network = None
        self.stream = None

    def write(self, network, filename):
        self.network = network
        self.stream = open(filename, 'w')

        self.stream.write("net {}\n")

        for i in range(self.network.getVariableCount()):
            self.writeVariableDescription(i)

        for i in range(self.network.getVariableCount()):
            v = self.network.get(i)
            if len(v.getParents()) == 0:
                self.writeRootVariable(v)
            else:
                self.writeNonrootVariable(v)

        self.stream.close()

    def writeVariableDescription(self, index):
        v = self.network.get(index)

        self.stream.write("node {} {{\n  states = (".format(v.getName()))

        for j in range(v.getArity()):
            self.stream.write('"{}" '.format(v.getValue(j)))

        self.stream.write(");\n")
        self.stream.write("}\n")

    def writeRootVariable(self, v):
        self.stream.write("potential ( {} ) {{\n".format(v.getName()))

        self.stream.write("  data = (")
        self.printProbabilities(v.getParameters(), 0)
        self.stream.write(");\n")
        self.stream.write("}\n")

    def writeNonrootVariable(self, v):
        self.stream.write("potential ( {} | {} ) {{\n".format(v.getName(), v.getParentsString()))
        self.stream.write("  data = ")

        ins = v.getFirstInstantiation()

        for i in range(len(v.getParents())+1):
            self.stream.write("(")

        for pIndex in range(v.getParametersSize()):
            pI = v.getParentIndex(ins)
            self.printProbabilities(v.getParameters(), pI)

            count = v.getNextParentInstantiation(ins)
            for i in range(count+1):
                self.stream.write(")")
            for i in range(count+1):
                self.stream.write("(")

        for i in range(len(v.getParents())+1):
            self.stream.write(")")

        self.stream.write(";\n")
        self.stream.write("}\n")

    def printProbabilities(self, values, pIndex):
           s = " ".join(["{:.4f}".format(val) for val in values[pIndex]])
           self.stream.write(s)
